//
//  ZLEmotionInputView.swift
//  表情键盘
//
//  Created by zhanglongtao on 17/1/13.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit

private let cellId = "cellid"
class ZLEmotionInputView: UIView {

    @IBOutlet weak var toolbar: ZLEmotionToolBar!
    @IBOutlet weak var collectionView: UICollectionView!
    //分页控件
    @IBOutlet weak var pageControl: UIPageControl!
    //选中表情回调闭包
    fileprivate var selectedEmotionCallback: ((_ enmotion: ZLEmotion?)->())?
    
    
    class func inputView(selectedEmotion: @escaping (_ enmotion: ZLEmotion?)->()) -> ZLEmotionInputView {
        let nib = UINib(nibName: "ZLEmotionInputView", bundle: nil)
        
        let v  = (nib.instantiate(withOwner: nil, options: nil)[0] as? ZLEmotionInputView)!
        
        v.selectedEmotionCallback = selectedEmotion
        
        return v
        
    }
    
    override func awakeFromNib() {
        
        
        //let nib = UINib(nibName: "ZLEmotionCell", bundle: nil)
        //collectionView.register(nib, forCellWithReuseIdentifier: cellId)
        //注册可重用的cell
        collectionView.register(ZLEmotionCell.classForCoder(), forCellWithReuseIdentifier: cellId)
        //设置工具栏代理
        toolbar.delegate = self
        
        //设置pageController的图像
        let bundle = EmotionManager.shared.bundle
        let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil)
        let selectImage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil)
        guard let normal = normalImage, let select = selectImage else{
            
            return
        }
        //pageControl.pageIndicatorTintColor = UIColor(patternImage: normal)
        //pageControl.currentPageIndicatorTintColor = UIColor(patternImage: select)
        //运行时获取属性  KVC赋值
        pageControl.setValue(normal, forKey: "_pageImage")
        pageControl.setValue(select, forKey: "_currentPageImage")
        
    }

}
// MARK --- ZLEmotionToolBarDelegate
extension ZLEmotionInputView: ZLEmotionToolBarDelegate {
    
    func emotionToolbarSelectedItem(toolbar: ZLEmotionToolBar, index: Int) {
        
        //让collectionView发生滚动
        let indexpath = IndexPath(item: 0, section: index)
        
        collectionView.scrollToItem(at: indexpath, at: .left, animated: true)
        //设置按钮的选中状态
        toolbar.selectedindex = index
    }
}
extension ZLEmotionInputView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    //分组数量 - 返回表情包的数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        print(EmotionManager.shared.packages)
        return EmotionManager.shared.packages.count
    }
    //返回每个分组中的表情‘页’的数量
    //每个分组的表情包中，表情也的数量 emotions 数组 / 20
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return EmotionManager.shared.packages[section].numberOfPages
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ZLEmotionCell
        
        cell.backgroundColor = UIColor.white
        
        //设置cell 
        cell.emotions = EmotionManager.shared.packages[indexPath.section].emotion(page: indexPath.item)
        
        //设置代理,不适合使用闭包
        cell.delegate = self
        
        //cell.label.text = "\(indexPath.section)-\(indexPath.row)"
        
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        
        //获取当前显示的cell的indexPath
        let paths = collectionView.indexPathsForVisibleItems
        
        //中心店在哪一个indexPath上在哪一个页面上
        var targetIndexPath: IndexPath?
        for idnexPath in paths{
            //根据indexPath货物cell
            let cell = collectionView.cellForItem(at: idnexPath)
            
            if cell?.frame.contains(center) == true{
                
                targetIndexPath = idnexPath
                
                break
            }
            
        }
        guard let target = targetIndexPath else{
            
            return
        }
        //判断是否找目标的index
        toolbar.selectedindex = target.section
        //设置分别控件
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item
        
    }
    
}
extension ZLEmotionInputView: ZLEmotionCellDlegate {
    
    func emotionCellDidSelectedEmotion(cell: ZLEmotionCell, em: ZLEmotion?) {
        
        //回调闭包选中的表情
        selectedEmotionCallback?(em)
        //print(em ?? "")
        //添加最近使用的表情
        guard let em = em else{
            return
        }
        
       
        //刷新数据
        //如果当前的collectionView就是最近的分组 不添加最近使用的表情
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0{
            
            return
        }
        
        EmotionManager.shared.recentEmotion(em: em)
        
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    }
}

